<template>
    <div class="team-management-container">
        <!-- 班组管理模块 -->
        <div class="team-section">
            <h2 class="section-title">班组</h2>

            <!-- 搜索和操作栏 -->
            <div class="search-action-bar">
                <div class="left-section">
                    <el-input v-model="teamSearchQuery" placeholder="班组名称" class="search-input" clearable />
                    <el-button type="primary" @click="searchTeams">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button type="primary" @click="advancedSearch">
                        <el-icon>
                            <Search />
                        </el-icon>
                        高级查询
                    </el-button>
                    <el-button type="success" @click="createNewTeam">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        新建
                    </el-button>
                </div>

                <div class="right-section">
                    <el-button type="info" @click="selectAllTeams" :disabled="teamList.length === 0">
                        <el-icon>
                            <Grid />
                        </el-icon>
                        全选
                    </el-button>
                    <el-button type="info" @click="clearTeamSelection" :disabled="selectedTeams.length === 0">
                        <el-icon>
                            <Close />
                        </el-icon>
                        清空选择
                    </el-button>
                    <el-button type="primary" @click="editTeam" :disabled="selectedTeams.length !== 1"
                        :title="selectedTeams.length === 1 ? '编辑选中的班组' : selectedTeams.length === 0 ? '请先选择要编辑的班组' : '只能选择一个班组进行编辑'">
                        <el-icon>
                            <Edit />
                        </el-icon>
                        编辑
                    </el-button>
                    <el-button type="danger" @click="deleteTeam" :disabled="selectedTeams.length === 0 || deleteLoading"
                        :loading="deleteLoading"
                        :title="selectedTeams.length > 0 ? `删除选中的 ${selectedTeams.length} 个班组` : '请先选择要删除的班组'">
                        <el-icon v-if="!deleteLoading">
                            <Delete />
                        </el-icon>
                        删除{{ selectedTeams.length > 0 ? `(${selectedTeams.length})` : '' }}
                    </el-button>
                    <el-button type="success" @click="importTeams">
                        <el-icon>
                            <Upload />
                        </el-icon>
                        导入
                    </el-button>
                    <el-button type="success" @click="exportTeams">
                        <el-icon>
                            <Download />
                        </el-icon>
                        导出
                    </el-button>
                    <el-button @click="showColumnSettings">
                        <el-icon>
                            <Grid />
                        </el-icon>
                    </el-button>
                    
                    <!-- 时间显示模式切换 -->
                    <el-switch
                        v-model="showRelativeTime"
                        active-text="相对时间"
                        inactive-text="绝对时间"
                        style="margin-left: 20px;"
                    />
                </div>
            </div>

            <!-- 高级查询条件区域 -->
            <div v-show="showAdvancedSearch" class="advanced-search-section">
                <div class="search-criteria">
                    <div class="criteria-item">
                        <label>班组名称:</label>
                        <el-input v-model="advancedSearchForm.teamName" placeholder="请输入班组名称" clearable
                            class="criteria-input" />
                    </div>
                    <div class="criteria-item">
                        <label>编组编码:</label>
                        <el-input v-model="advancedSearchForm.teamCode" placeholder="请输入编组编码" clearable
                            class="criteria-input" />
                    </div>
                    <div class="criteria-item">
                        <label>班组类型:</label>
                        <el-select v-model="advancedSearchForm.teamTypeName" placeholder="请选择班组类型" clearable
                            class="criteria-select">
                            <el-option v-for="item in teamTypeList" :key="item.TeamTypeId" :label="item.TeamTypeName"
                                :value="item.TeamTypeName" />
                        </el-select>
                    </div>
                </div>
                <div class="search-actions">
                    <el-button type="primary" @click="executeAdvancedSearch">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button @click="resetAdvancedSearch">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                    <el-button @click="closeAdvancedSearch">
                        <el-icon>
                            <Close />
                        </el-icon>
                        关闭
                    </el-button>
                </div>
            </div>

            <!-- 选择状态显示 -->
            <div class="info-status-bar">
                <div v-if="selectedTeams.length > 0" class="selection-status">
                    <el-tag type="info" effect="plain">
                        已选择 {{ selectedTeams.length }} 个班组
                    </el-tag>
                    <el-button type="text" size="small" @click="clearTeamSelection">
                        清空选择
                    </el-button>
                </div>
            </div>

            <!-- 班组列表表格 -->
            <el-table :data="teamList" style="width: 100%" @selection-change="handleTeamSelectionChange"
                @row-click="handleTeamRowClick" border stripe v-loading="loading" highlight-current-row
                ref="teamTableRef">
                <el-table-column type="selection" width="55" :selectable="(row: any) => row.TeamsId" />

                <!-- 动态列显示 -->
                <template v-for="column in columnSettings.filter(col => col.visible).sort((a, b) => a.order - b.order)"
                    :key="column.key">
                    <!-- 班组名称列 -->
                    <el-table-column v-if="column.key === 'TeamName'" prop="TeamName" :label="column.label" sortable
                        :width="column.width" min-width="120" />

                    <!-- 编组编码列 -->
                    <el-table-column v-if="column.key === 'TeamCode'" prop="TeamCode" :label="column.label" sortable
                        :width="column.width" min-width="120">
                        <template #default="scope">
                            <span 
                                class="clickable-team-code" 
                                @click="handleTeamCodeClick(scope.row)"
                                :title="`点击编辑 ${scope.row.TeamName || '班组'}`"
                            >
                                {{ scope.row.TeamCode }}
                            </span>
                        </template>
                    </el-table-column>

                    <!-- 班组类型列 -->
                    <el-table-column v-if="column.key === 'TeamTypeName'" :label="column.label" sortable
                        :width="column.width" min-width="100">
                        <template #default="scope">
                            <el-tag :type="getTeamTypeTagType(scope.row.TeamTypeName)" effect="light" size="small"
                                class="team-type-tag">
                                {{ scope.row.TeamTypeName }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <!-- 备注列 -->
                    <el-table-column v-if="column.key === 'Remark'" prop="Remark" :label="column.label"
                        :width="column.width" min-width="150" show-overflow-tooltip />

                    <!-- 创建人列 -->
                    <el-table-column v-if="column.key === 'Creator'" prop="Creator" :label="column.label" sortable
                        :width="column.width" min-width="100" />

                    <!-- 创建时间列 -->
                    <el-table-column v-if="column.key === 'CreatedTime'" :label="column.label" sortable
                        :width="column.width" min-width="150">
                        <template #default="scope">
                            {{ showRelativeTime ? getRelativeTime(scope.row.CreatedTime) : formatDateTime(scope.row.CreatedTime) }}
                        </template>
                    </el-table-column>

                    <!-- 修改人列 -->
                    <el-table-column v-if="column.key === 'Modifier'" :label="column.label" sortable
                        :width="column.width" min-width="100" />

                    <!-- 修改时间列 -->
                    <el-table-column v-if="column.key === 'ModifiedTime'" :label="column.label" sortable
                        :width="column.width" min-width="150">
                        <template #default="scope">
                            {{ scope.row.ModifiedTime ? (showRelativeTime ? getRelativeTime(scope.row.ModifiedTime) : formatDateTime(scope.row.ModifiedTime)) : '-' }}
                        </template>
                    </el-table-column>
                </template>
            </el-table>

            <!-- 分页控件 -->
            <div class="pagination-container">
                <span class="total-count">共{{ totalTeams }}条</span>
                <el-select v-model="pageSize" class="page-size-select" @change="handlePageSizeChange">
                    <el-option label="5条/页" :value="5" />
                    <el-option label="10条/页" :value="10" />
                    <el-option label="20条/页" :value="20" />
                    <el-option label="30条/页" :value="30" />
                </el-select>
                <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="totalTeams"
                    :page-count="totalPages" layout="prev, pager, next" @current-change="handlePageChange" />
                <span class="go-to-page">
                    前往
                    <el-input v-model="goToPage" class="page-input" @keyup.enter="goToSpecificPage" />
                    页
                </span>
            </div>
        </div>

        <!-- 班组-成员管理模块 -->
        <div class="team-member-section">
            <h2 class="section-title">班组-成员</h2>
            
            <!-- 时间显示模式切换 -->
            <div class="time-display-toggle">
                <el-switch
                    v-model="showRelativeTime"
                    active-text="相对时间"
                    inactive-text="绝对时间"
                    style="margin-bottom: 15px;"
                />
            </div>

            <!-- 成员列表表格 -->
            <el-table :data="memberList" style="width: 100%" @selection-change="handleMemberSelectionChange" border
                stripe v-loading="loading">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="MemberName" label="成员名称" sortable />
                <el-table-column prop="MemberRealName" label="成员姓名" sortable />
                <el-table-column prop="PhoneNumber" label="电话号码" sortable />
                <el-table-column prop="Creator" label="创建人" sortable />
                <el-table-column label="创建时间" sortable>
                    <template #default="scope">
                        <span>{{ showRelativeTime ? getRelativeTime(scope.row.CreatedTime) : formatDateTime(scope.row.CreatedTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="Modifier" label="修改人" sortable>
                    <template #default="scope">
                        <span>{{ scope.row.Modifier || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="修改时间" sortable>
                    <template #default="scope">
                        <span>{{ scope.row.ModifiedTime ? (showRelativeTime ? getRelativeTime(scope.row.ModifiedTime) : formatDateTime(scope.row.ModifiedTime)) : '-' }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 成员分页控件 -->
            <div class="pagination-container">
                <span class="total-count">共{{ totalMembers }}条</span>
                <el-select v-model="memberPageSize" class="page-size-select">
                    <el-option label="5条/页" :value="5" />
                    <el-option label="10条/页" :value="10" />
                    <el-option label="20条/页" :value="20" />
                    <el-option label="30条/页" :value="30" />
                </el-select>
                <el-pagination v-model:current-page="memberCurrentPage" :page-size="memberPageSize"
                    :total="totalMembers" layout="prev, pager, next" @current-change="handleMemberPageChange" />
                <span class="go-to-page">
                    前往
                    <el-input v-model="memberGoToPage" class="page-input" @keyup.enter="goToSpecificMemberPage" />
                    页
                </span>
            </div>
        </div>
    </div>

    <!-- 导入对话框 -->
    <el-dialog v-model="showImportDialog" title="班组-导入" width="500px" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="import-dialog-content">
            <!-- 操作按钮 -->
            <div class="import-actions">
                <el-button type="primary" @click="downloadTemplate">
                    <el-icon>
                        <Download />
                    </el-icon>
                    下载模板
                </el-button>
            </div>

            <!-- 文件选择区域 -->
            <div class="file-upload-area">
                <el-upload ref="uploadRef" :auto-upload="false" :show-file-list="false" :on-change="handleFileSelect"
                    accept=".xlsx,.xls" drag>
                    <el-icon class="el-icon--upload">
                        <Upload />
                    </el-icon>
                    <div class="el-upload__text">
                        将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传Excel文件，且不超过10MB
                        </div>
                    </template>
                </el-upload>
            </div>

            <!-- 已选择文件显示 -->
            <div v-if="importFile" class="selected-file">
                <el-tag type="success" effect="plain">
                    已选择: {{ importFile.name }}
                </el-tag>
                <span class="file-size">
                    ({{ (importFile.size / 1024 / 1024).toFixed(2) }}MB)
                </span>
            </div>

            <!-- 上传说明 -->
            <div class="upload-instructions">
                <el-alert title="上传说明" type="warning" :closable="false" show-icon>
                    <template #default>
                        <p>只能上传Excel文件(.xlsx或.xls)</p>
                        <p>文件大小不能超过10MB</p>
                        <p>请先下载模板，按照模板格式填写数据</p>
                    </template>
                </el-alert>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeImportDialog">取消</el-button>
                <el-button type="primary" @click="uploadFile" :loading="importLoading" :disabled="!importFile">
                    上传文件
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog v-model="showImportResult" title="导入结果详情" width="600px" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="import-result-content">
            <!-- 导入统计信息 -->
            <div class="import-summary">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <div class="summary-item">
                            <div class="summary-number">{{ importResult?.TotalCount || 0 }}</div>
                            <div class="summary-label">总记录数</div>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="summary-item success">
                            <div class="summary-number">{{ importResult?.SuccessCount || 0 }}</div>
                            <div class="summary-label">成功数量</div>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="summary-item danger">
                            <div class="summary-number">{{ importResult?.FailureCount || 0 }}</div>
                            <div class="summary-label">失败数量</div>
                        </div>
                    </el-col>
                </el-row>
            </div>

            <!-- 成功导入的班组ID -->
            <div v-if="importResult?.SuccessTeamIds && importResult.SuccessTeamIds.length > 0" class="success-section">
                <h4>成功导入的班组ID：</h4>
                <el-tag v-for="teamId in importResult.SuccessTeamIds" :key="teamId" type="success" effect="plain"
                    class="team-id-tag">
                    {{ teamId }}
                </el-tag>
            </div>

            <!-- 失败行号 -->
            <div v-if="importResult?.FailureRowNumbers && importResult.FailureRowNumbers.length > 0"
                class="failure-section">
                <h4>失败的行号：</h4>
                <el-tag v-for="rowNum in importResult.FailureRowNumbers" :key="rowNum" type="danger" effect="plain"
                    class="row-number-tag">
                    第{{ rowNum }}行
                </el-tag>
            </div>

            <!-- 详细错误信息 -->
            <div v-if="importResult?.ErrorMessages && importResult.ErrorMessages.length > 0" class="error-section">
                <h4>详细错误信息：</h4>
                <div class="error-list">
                    <div v-for="(error, index) in importResult.ErrorMessages" :key="index" class="error-item">
                        <el-icon class="error-icon">
                            <Close />
                        </el-icon>
                        <span class="error-text">{{ error }}</span>
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeImportResult" type="primary">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 列设置对话框 -->
    <el-dialog v-model="showColumnSettingsDialog" title="设置" width="600px" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="column-settings-content">
            <!-- 操作提示 -->
            <el-alert title="拖动列名可调整表格列显示顺序" type="success" :closable="false" show-icon class="drag-tip" />

            <!-- 列设置列表 -->
            <div class="column-list">
                <el-table :data="columnSettings" style="width: 100%" border>
                    <el-table-column prop="order" label="#" width="60" align="center" />
                    <el-table-column prop="label" label="列名" />
                    <el-table-column label="是否显示" width="100" align="center">
                        <template #default="scope">
                            <el-checkbox v-model="scope.row.visible" :label="scope.row.visible ? '显示' : '隐藏'" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center">
                        <template #default="scope">
                            <div class="drag-handle" draggable="true" @dragstart="onDragStart($event, scope.$index)"
                                @dragover="onDragOver($event)" @drop="onDrop($event, scope.$index)" title="拖拽调整顺序">
                                <el-icon>
                                    <Grid />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeColumnSettings">取消</el-button>
                <el-button type="success" @click="resetColumnSettings">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    重置
                </el-button>
                <el-button type="primary" @click="confirmColumnSettings">
                    <el-icon>
                        <Check />
                    </el-icon>
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 班组新增对话框 -->
    <el-dialog v-model="showCreateTeamDialog" title="班组(新建)" width="1200px" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="create-team-content">
            <!-- 班组信息部分 -->
            <div class="team-info-section">
                <h3 class="section-subtitle">班组信息</h3>
                <el-form :model="createTeamForm" :rules="createTeamRules" ref="createTeamFormRef" label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="班组名称" prop="TeamName" required>
                                <el-input v-model="createTeamForm.TeamName" placeholder="请输入班组名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="编组编码" prop="TeamCode">
                                <el-input v-model="createTeamForm.TeamCode" placeholder="请输入,忽略将自动生成" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="班组类型" prop="TeamTypeId" required>
                                <el-select v-model="createTeamForm.TeamTypeId" placeholder="请选择班组类型" style="width: 100%">
                                    <el-option v-for="item in teamTypeList" :key="item.TeamTypeId" 
                                        :label="item.TeamTypeName" :value="item.TeamTypeId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注" prop="Remark">
                                <el-input v-model="createTeamForm.Remark" type="textarea" placeholder="备注" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 班组成员部分 -->
            <div class="team-member-section">
                <h3 class="section-subtitle">
                    <el-icon><Grid /></el-icon>
                    班组成员
                </h3>
                
                <!-- 操作按钮 -->
                <div class="member-actions">
                    <el-button type="primary" @click="selectExistingUsers">
                        <el-icon><Plus /></el-icon>
                        +选择用户
                    </el-button>
                    <el-button type="success" @click="addMemberRow">
                        <el-icon><Plus /></el-icon>
                        +添加行
                    </el-button>
                    <el-button type="danger" @click="deleteSelectedRows" :disabled="selectedMemberRows.length === 0">
                        <el-icon><Delete /></el-icon>
                        删除行
                    </el-button>
                    
                    <el-button @click="refreshMemberTable">
                        <el-icon><Refresh /></el-icon>
                        刷新
                    </el-button>
                    
                    <!-- 时间显示模式切换 -->
                    <el-switch
                        v-model="showRelativeTime"
                        active-text="相对时间"
                        inactive-text="绝对时间"
                        style="margin-left: 20px;"
                    />
                </div>

                <!-- 成员表格 -->
                <el-table :data="memberTableData" style="width: 100%" @selection-change="handleMemberRowSelectionChange" 
                    border stripe>
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="*成员名称" prop="MemberName" sortable min-width="120">
                        <template #default="scope">
                            <el-input v-model="scope.row.MemberName" placeholder="请输入成员名称" />
                        </template>
                    </el-table-column>
                    <el-table-column label="*成员姓名" prop="MemberRealName" sortable min-width="120">
                        <template #default="scope">
                            <el-input v-model="scope.row.MemberRealName" placeholder="请输入成员姓名" />
                        </template>
                    </el-table-column>
                    <el-table-column label="电话号码" prop="PhoneNumber" min-width="120">
                        <template #default="scope">
                            <el-input v-model="scope.row.PhoneNumber" placeholder="请输入电话号码" />
                        </template>
                    </el-table-column>
                    <el-table-column label="创建人" prop="Creator" min-width="100">
                        <template #default="scope">
                            <el-input v-model="scope.row.Creator" placeholder="创建人" />
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="CreatedTime" min-width="150">
                        <template #default="scope">
                            <span>{{ showRelativeTime ? getRelativeTime(scope.row.CreatedTime) : formatDateTime(scope.row.CreatedTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Modifier" label="修改人" min-width="100">
                        <template #default="scope">
                            <span>{{ scope.row.Modifier || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="ModifiedTime" label="修改时间" min-width="150">
                        <template #default="scope">
                            <span>{{ scope.row.ModifiedTime ? (showRelativeTime ? getRelativeTime(scope.row.ModifiedTime) : formatDateTime(scope.row.ModifiedTime)) : '-' }}</span>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页信息 -->
                <div class="member-pagination">
                    <span class="total-count">共{{ memberTableData.length }}条</span>
                    <el-select v-model="memberTablePageSize" class="page-size-select">
                        <el-option label="100条/页" :value="100" />
                    </el-select>
                    <el-pagination v-model:current-page="memberTableCurrentPage" :page-size="memberTablePageSize" 
                        :total="memberTableData.length" layout="prev, pager, next" />
                    <span class="go-to-page">
                        前往
                        <el-input v-model="memberTableGoToPage" class="page-input" @keyup.enter="goToSpecificMemberTablePage" />
                        页
                    </span>
                </div>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeCreateTeamDialog">关闭</el-button>
                <el-button type="primary" @click="saveTeam" :loading="saveLoading">
                    <el-icon><Check /></el-icon>
                    保存
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 选择用户对话框 -->
    <el-dialog v-model="showSelectUsersDialog" title="选择用户" width="800px" :close-on-click-modal="false">
        <div class="select-users-content">
            <div class="user-search-bar">
                <el-input v-model="userSearchQuery" placeholder="搜索用户名或姓名" style="width: 300px" clearable />
                <el-button type="primary" @click="searchUsers">
                    <el-icon><Search /></el-icon>
                    搜索
                </el-button>
            </div>
            
            <el-table :data="userList" style="width: 100%" @selection-change="handleUserSelectionChange" border>
                <el-table-column type="selection" width="55" />
                <el-table-column prop="Account" label="用户名" />
                <el-table-column prop="Name" label="姓名" />
                <el-table-column prop="QQNumber1" label="电话号码" />
                <el-table-column prop="Role" label="角色" />
            </el-table>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeSelectUsersDialog">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelectUsers">
                    {{ isSelectingForEdit ? '添加到编辑表格' : '确定' }}
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 班组编辑对话框 -->
    <el-dialog v-model="showEditTeamDialog" title="① 编辑" width="1200px" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="edit-team-content">
            <!-- 班组信息部分 -->
            <div class="team-info-section">
                <h3 class="section-subtitle">班组信息</h3>
                <el-form :model="editTeamForm" :rules="editTeamRules" ref="editTeamFormRef" label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="班组名称" prop="TeamName" required>
                                <el-input v-model="editTeamForm.TeamName" placeholder="请输入班组名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="编组编码" prop="TeamCode">
                                <el-input v-model="editTeamForm.TeamCode" placeholder="请输入编组编码" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="班组类型" prop="TeamTypeId" required>
                                <el-select v-model="editTeamForm.TeamTypeId" placeholder="请选择班组类型" style="width: 100%">
                                    <el-option v-for="item in teamTypeList" :key="item.TeamTypeId" 
                                        :label="item.TeamTypeName" :value="item.TeamTypeId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注" prop="Remark">
                                <el-input v-model="editTeamForm.Remark" type="textarea" placeholder="备注" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 班组成员部分 -->
            <div class="team-member-section">
                <h3 class="section-subtitle">
                    <el-icon><Grid /></el-icon>
                    ■ 班组成员
                </h3>
                
                                 <!-- 操作按钮 -->
                 <div class="member-actions">
                     <el-button type="primary" @click="selectExistingUsersForEdit">
                         <el-icon><Plus /></el-icon>
                         +选择用户
                     </el-button>
                     <el-button type="success" @click="addEditMemberRow">
                         <el-icon><Plus /></el-icon>
                         +添加行
                     </el-button>
                     <el-button type="danger" @click="deleteSelectedEditRows" :disabled="selectedEditMemberRows.length === 0">
                         <el-icon><Delete /></el-icon>
                         删除行
                     </el-button>

                     <el-button @click="exportEditMembers">
                         <el-icon><Download /></el-icon>
                         导出
                     </el-button>
                     <el-button @click="refreshEditMemberTable">
                         <el-icon><Refresh /></el-icon>
                         刷新
                     </el-button>
                 </div>
                 


                                 <!-- 成员表格 -->
                 <el-table :data="editMemberTableData" style="width: 100%" @selection-change="handleEditMemberRowSelectionChange" 
                     border stripe>
                     <el-table-column type="selection" width="55" />
                     <el-table-column label="成员ID" prop="TeamMembersId" width="80" align="center">
                         <template #default="scope">
                             <span v-if="scope.row.TeamMembersId">{{ scope.row.TeamMembersId }}</span>
                             <el-tag v-else type="info" size="small">新成员</el-tag>
                         </template>
                     </el-table-column>
                     <el-table-column label="*成员名称" prop="MemberName" sortable min-width="120">
                         <template #default="scope">
                             <el-input v-model="scope.row.MemberName" placeholder="请输入成员名称" />
                         </template>
                     </el-table-column>
                     <el-table-column label="*成员姓名" prop="MemberRealName" sortable min-width="120">
                         <template #default="scope">
                             <el-input v-model="scope.row.MemberRealName" placeholder="请输入成员姓名" />
                         </template>
                     </el-table-column>
                     <el-table-column label="电话号码" prop="PhoneNumber" sortable min-width="120">
                         <template #default="scope">
                             <el-input v-model="scope.row.PhoneNumber" placeholder="请输入电话号码" />
                         </template>
                     </el-table-column>
                     <el-table-column label="创建人" prop="Creator" sortable min-width="120" />
                     <el-table-column label="创建时间" prop="CreatedTime" sortable min-width="160">
                         <template #default="scope">
                             {{ showRelativeTime ? getRelativeTime(scope.row.CreatedTime) : formatDateTime(scope.row.CreatedTime) }}
                         </template>
                     </el-table-column>
                     <el-table-column label="修改人" prop="Modifier" sortable min-width="120" />
                     <el-table-column label="修改时间" prop="ModifiedTime" sortable min-width="160">
                         <template #default="scope">
                             {{ showRelativeTime ? getRelativeTime(scope.row.ModifiedTime) : formatDateTime(scope.row.ModifiedTime) }}
                         </template>
                     </el-table-column>
                 </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination
                        v-model:current-page="editMemberTableCurrentPage"
                        v-model:page-size="editMemberTablePageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="editMemberTableTotal"
                        layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleEditMemberSizeChange"
                        @current-change="handleEditMemberCurrentChange"
                    />
                </div>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button type="success" @click="saveEditTeam">
                    <el-icon><Check /></el-icon>
                    √ 保存
                </el-button>
                <el-button type="primary" @click="closeEditTeamDialog">
                    <el-icon><Close /></el-icon>
                    × 关闭
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Grid, Search, Refresh, Close, Plus, Edit, Delete, Upload, Download, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { MES_XHY_ApiHost } from '@/utils/Interceptors'

// 时间格式化工具函数
const formatDateTime = (dateTimeString: string) => {
    if (!dateTimeString) return ''
    
    try {
        let date: Date
        
        // 处理不同的时间格式
        if (dateTimeString.includes('T')) {
            // ISO格式: 2025-08-18T13:58:45 或 2025-08-18T06:14:06.224Z
            date = new Date(dateTimeString)
        } else if (dateTimeString.includes('-')) {
            // 标准日期格式: 2025-08-18 13:58:45
            date = new Date(dateTimeString.replace(' ', 'T'))
        } else {
            // 其他格式，尝试直接解析
            date = new Date(dateTimeString)
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
            return dateTimeString // 如果解析失败，返回原字符串
        }
        
        // 格式化日期时间
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        
        // 返回格式化的时间字符串
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        
    } catch (error) {
        console.warn('时间格式化失败:', error, '原始值:', dateTimeString)
        return dateTimeString // 如果出错，返回原字符串
    }
}

// 获取相对时间描述（可选功能）
const getRelativeTime = (dateTimeString: string) => {
    if (!dateTimeString) return ''
    
    try {
        const date = new Date(dateTimeString)
        if (isNaN(date.getTime())) return dateTimeString
        
        const now = new Date()
        const diffMs = now.getTime() - date.getTime()
        const diffMinutes = Math.floor(diffMs / (1000 * 60))
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
        
        if (diffMinutes < 1) return '刚刚'
        if (diffMinutes < 60) return `${diffMinutes}分钟前`
        if (diffHours < 24) return `${diffHours}小时前`
        if (diffDays < 7) return `${diffDays}天前`
        
        // 超过7天显示具体日期
        return formatDateTime(dateTimeString)
        
    } catch (error) {
        return formatDateTime(dateTimeString)
    }
}

// 班组相关数据
const teamSearchQuery = ref('')
const teamList = ref([])
const totalTeams = ref(0)
const totalPages = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
const goToPage = ref('')
const loading = ref(false)
const deleteLoading = ref(false)

// 班组类型数据
const teamTypeList = ref<any[]>([])

// 高级查询相关数据
const showAdvancedSearch = ref(false)
const advancedSearchForm = reactive({
    teamName: '',
    teamCode: '',
    teamTypeName: '',
    pageIndex: 1,
    pageSize: 5
})

// 班组-成员相关数据
const memberList = ref([])
const totalMembers = ref(0)
const memberCurrentPage = ref(1)
const memberPageSize = ref(5)
const memberGoToPage = ref('')

// 选中的班组和成员
const selectedTeams = ref<any[]>([])
const selectedMembers = ref<any[]>([])

// 表格引用
const teamTableRef = ref()
const uploadRef = ref()

// 当前选中的班组ID
const currentSelectedTeamId = ref<number | null>(null)

// 班组新增相关状态
const showCreateTeamDialog = ref(false)
const createTeamFormRef = ref()
const saveLoading = ref(false)
const createTeamForm = reactive({
    TeamName: '',
    TeamCode: '',
    TeamTypeId: null as number | null,
    Remark: '',
    Creator: 'admin' // 默认值
})

// 班组新增表单验证规则
const createTeamRules = {
    TeamName: [
        { required: true, message: '请输入班组名称', trigger: 'blur' }
    ],
    TeamTypeId: [
        { required: true, message: '请选择班组类型', trigger: 'change' }
    ]
}

// 班组成员表格相关状态
const memberTableData = ref<any[]>([])
const selectedMemberRows = ref<any[]>([])
const memberTableCurrentPage = ref(1)
const memberTablePageSize = ref(100)
const memberTableGoToPage = ref('')
const showRelativeTime = ref(false) // 时间显示模式：true为相对时间，false为绝对时间

// 选择用户对话框相关状态
const showSelectUsersDialog = ref(false)
const userSearchQuery = ref('')
const isSelectingForEdit = ref(false) // 标识是否在编辑对话框中选择用户

// 班组编辑相关状态
const showEditTeamDialog = ref(false)
const editTeamFormRef = ref()
const editSaveLoading = ref(false)
const editTeamForm = reactive({
    TeamsId: 0,
    TeamName: '',
    TeamCode: '',
    TeamTypeId: null as number | null,
    Remark: '',
    Modifier: 'admin' // 默认值
})

// 班组编辑表单验证规则
const editTeamRules = {
    TeamName: [
        { required: true, message: '请输入班组名称', trigger: 'blur' }
    ],
    TeamTypeId: [
        { required: true, message: '请选择班组类型', trigger: 'change' }
    ]
}

// 编辑班组成员表格相关状态
const editMemberTableData = ref<any[]>([])
const selectedEditMemberRows = ref<any[]>([])
const editMemberTableCurrentPage = ref(1)
const editMemberTablePageSize = ref(100)
const editMemberTableGoToPage = ref('')
const editMemberTableTotal = ref(0)
const userList = ref<any[]>([])
const selectedUsers = ref<any[]>([])


// 获取班组类型列表
const getTeamTypeList = async () => {
    try {
        const response = await MES_XHY_ApiHost.get(`/api/Scheduling/GetTeamTypeList`)

        if (response.data.code === 200) {
            teamTypeList.value = response.data.data
        } else {
            ElMessage.error(`获取班组类型失败: ${response.data.msg || '未知错误'}`)
        }
    } catch (error: any) {
        console.error('获取班组类型出错:', error)
        if (error.response) {
            ElMessage.error(`获取班组类型失败: ${error.response.status} - ${error.response.statusText}`)
        } else if (error.request) {
            ElMessage.error('获取班组类型失败，请检查网络连接')
        } else {
            ElMessage.error('获取班组类型失败，请检查网络连接')
        }
    }
}

// 获取班组列表
const getTeamList = async (params: any = {}) => {
    loading.value = true
    try {
        const queryParams = {
            TeamName: params.teamName || '',
            TeamCode: params.teamCode || '',
            TeamTypeName: params.teamTypeName || '',
            PageIndex: params.pageIndex || currentPage.value,
            PageSize: params.pageSize || pageSize.value
        }

        const response = await MES_XHY_ApiHost.get(`/api/Scheduling/GetTeamsList`, {
            params: queryParams
        })

        if (response.data.code === 200) {
            teamList.value = response.data.PageData
            totalTeams.value = response.data.TotalCount
            totalPages.value = response.data.TotalPage
            currentPage.value = queryParams.PageIndex

            if (teamList.value.length === 0) {
                ElMessage.info('暂无数据')
            }
        } else {
            ElMessage.error(`获取班组列表失败: ${response.data.msg || '未知错误'}`)
        }
    } catch (error: any) {
        console.error('获取班组列表出错:', error)
        if (error.response) {
            ElMessage.error(`获取班组列表失败: ${error.response.status} - ${error.response.statusText}`)
        } else if (error.request) {
            ElMessage.error('获取班组列表失败，请检查网络连接')
        } else {
            ElMessage.error('获取班组列表失败，请检查网络连接')
        }
    } finally {
        loading.value = false
    }
}

// 班组相关方法
const searchTeams = () => {
    currentPage.value = 1
    getTeamList({
        teamName: teamSearchQuery.value,
        pageIndex: 1
    })
}

const advancedSearch = () => {
    showAdvancedSearch.value = true
}

const executeAdvancedSearch = () => {
    currentPage.value = 1
    getTeamList({
        teamName: advancedSearchForm.teamName,
        teamCode: advancedSearchForm.teamCode,
        teamTypeName: advancedSearchForm.teamTypeName,
        pageIndex: 1
    })
    showAdvancedSearch.value = false
}

const resetAdvancedSearch = () => {
    Object.assign(advancedSearchForm, {
        teamName: '',
        teamCode: '',
        teamTypeName: '',
        pageIndex: 1,
        pageSize: 5
    })
}

const closeAdvancedSearch = () => {
    showAdvancedSearch.value = false
}

const createNewTeam = () => {
    showCreateTeam()
}

const editTeam = () => {
    if (selectedTeams.value.length === 0) {
        ElMessage.warning('请先选择要编辑的班组')
        return
    }

    if (selectedTeams.value.length > 1) {
        ElMessage.warning('只能选择一个班组进行编辑')
        return
    }

    const selectedTeam = selectedTeams.value[0]
    console.log('编辑班组:', selectedTeam)
    
    // 填充编辑表单数据
    Object.assign(editTeamForm, {
        TeamsId: selectedTeam.TeamsId,
        TeamName: selectedTeam.TeamName,
        TeamCode: selectedTeam.TeamCode,
        TeamTypeId: selectedTeam.TeamTypeId,
        Remark: selectedTeam.Remark || '',
        Modifier: 'admin' // 可以从登录用户信息获取
    })
    
    // 获取班组成员数据
    getEditTeamMembers(selectedTeam.TeamsId)
    
    // 显示编辑对话框
    showEditTeamDialog.value = true
}

const deleteTeam = async () => {
    if (selectedTeams.value.length === 0) {
        ElMessage.warning('请先选择要删除的班组')
        return
    }

    // 验证选中的班组数据
    const invalidTeams = selectedTeams.value.filter(team => !team.TeamsId || !team.TeamName)
    if (invalidTeams.length > 0) {
        ElMessage.error('选中的班组数据不完整，请重新选择')
        console.error('无效的班组数据:', invalidTeams)
        return
    }

    // 先测试API连接
    try {
        const testResponse = await MES_XHY_ApiHost.get('/api/Scheduling/GetTeamsList?PageIndex=1&PageSize=1')
        console.log('API连接测试成功:', testResponse.status)
    } catch (testError: any) {
        console.error('API连接测试失败:', testError.response?.status)
        ElMessage.error('无法连接到API服务器，请检查网络连接')
        return
    }

    try {
        // 显示确认对话框
        const teamNames = selectedTeams.value.map(team => team.TeamName).join('、')
        const operationInfo = `班组数量: ${selectedTeams.value.length}个`

        await ElMessageBox.confirm(
            `确定要删除以下班组吗？<br><br><strong>${teamNames}</strong><br><br>${operationInfo}<br><br>此操作不可恢复，将同时删除相关成员信息！`,
            '确认删除班组',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true,
                customClass: 'delete-confirm-dialog'
            }
        )

        // 设置删除加载状态
        deleteLoading.value = true

        // 准备删除参数
        const teamsIds = selectedTeams.value.map(team => {
            // 确保ID是数字类型
            const id = parseInt(team.TeamsId)
            if (isNaN(id)) {
                throw new Error(`无效的班组ID: ${team.TeamsId}`)
            }
            return id
        })

        // 构建删除参数
        const deleteParams = {
            TeamsIds: teamsIds,
            UserId: 0
        }



        console.log('删除参数:', deleteParams)
        console.log('参数类型检查:', {
            TeamsIds: Array.isArray(teamsIds),
            TeamsIdsLength: teamsIds.length,
            TeamsIdsType: typeof teamsIds[0],
            UserIdType: typeof deleteParams.UserId
        })

        // 调用批量删除API
        console.log('发送删除请求到:', '/api/Scheduling/BatchDeleteTeams')
        console.log('请求参数:', deleteParams)
        console.log('请求参数JSON:', JSON.stringify(deleteParams))

        // 检查是否有token
        const token = localStorage.getItem('token')
        console.log('当前token:', token ? '存在' : '不存在')

        // 验证参数完整性
        if (!Array.isArray(deleteParams.TeamsIds) || deleteParams.TeamsIds.length === 0) {
            throw new Error('TeamsIds字段必须是包含至少一个ID的数组')
        }

        const response = await MES_XHY_ApiHost.post('/api/Scheduling/BatchDeleteTeams', deleteParams)

        if (response.data.code === 200) {
            ElMessage.success(response.data.msg || '删除成功')

            // 清空选中状态
            selectedTeams.value = []

            // 重新获取班组列表
            await getTeamList({
                teamName: teamSearchQuery.value,
                teamCode: advancedSearchForm.teamCode,
                teamTypeName: advancedSearchForm.teamTypeName,
                pageIndex: currentPage.value,
                pageSize: pageSize.value
            })

            // 如果当前选中的班组被删除，清空成员列表
            if (currentSelectedTeamId.value && teamsIds.includes(currentSelectedTeamId.value)) {
                memberList.value = []
                totalMembers.value = 0
                currentSelectedTeamId.value = null
            }

            // 显示删除操作记录
            console.log(`成功删除了 ${teamsIds.length} 个班组`)
        } else {
            ElMessage.error(`删除失败: ${response.data.msg || '未知错误'}`)
        }
    } catch (error: any) {
        if (error === 'cancel') {
            // 用户取消删除操作
            return
        }

        console.error('删除班组出错:', error)
        if (error.response) {
            console.error('错误响应数据:', error.response.data)
            console.error('错误状态:', error.response.status)
            console.error('错误状态文本:', error.response.statusText)

            // 尝试获取更详细的错误信息
            let errorMsg = `删除班组失败: ${error.response.status} - ${error.response.statusText}`
            if (error.response.data && error.response.data.msg) {
                errorMsg = `删除班组失败: ${error.response.data.msg}`
            } else if (error.response.data && error.response.data.message) {
                errorMsg = `删除班组失败: ${error.response.data.message}`
            }

            ElMessage.error(errorMsg)
        } else if (error.request) {
            ElMessage.error('删除班组失败，请检查网络连接')
        } else {
            ElMessage.error('删除班组失败，请检查网络连接')
        }
    } finally {
        // 重置删除加载状态
        deleteLoading.value = false
    }
}

// 导入相关状态
const showImportDialog = ref(false)
const importFile = ref<File | null>(null)
const importLoading = ref(false)
const importResult = ref<any>(null)
const showImportResult = ref(false)

// 列设置相关状态
const showColumnSettingsDialog = ref(false)
const columnSettings = ref([
    { key: 'TeamName', label: '班组名称', visible: true, order: 1, width: 140 },
    { key: 'TeamCode', label: '编组编码', visible: true, order: 2, width: 140 },
    { key: 'TeamTypeName', label: '班组类型', visible: true, order: 3, width: 120 },
    { key: 'Remark', label: '备注', visible: true, order: 4, width: 180 },
    { key: 'Creator', label: '创建人', visible: true, order: 5, width: 120 },
    { key: 'CreatedTime', label: '创建时间', visible: true, order: 6, width: 160 },
    { key: 'Modifier', label: '修改人', visible: true, order: 7, width: 160 },
    { key: 'ModifiedTime', label: '修改时间', visible: true, order: 8, width: 160 }
])

// 下载模板
const downloadTemplate = async () => {
    let loadingInstance: any = null

    try {
        loadingInstance = ElLoading.service({
            lock: true,
            text: '正在下载模板...',
            background: 'rgba(0, 0, 0, 0.7)'
        })

        // 调用下载模板API
        const response = await MES_XHY_ApiHost.get('/api/Scheduling/DownloadTeamsImportTemplate', {
            responseType: 'blob'
        })

        if (response.status === 200) {
            // 创建下载链接
            const blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })

            // 生成文件名
            const fileName = '班组导入模板.xlsx'

            // 创建下载链接并触发下载
            const downloadLink = document.createElement('a')
            downloadLink.href = URL.createObjectURL(blob)
            downloadLink.download = fileName
            document.body.appendChild(downloadLink)
            downloadLink.click()
            document.body.removeChild(downloadLink)

            // 释放URL对象
            URL.revokeObjectURL(downloadLink.href)

            ElMessage.success('模板下载成功！')
            console.log('模板下载成功:', fileName)
        } else {
            throw new Error(`下载失败，状态码: ${response.status}`)
        }

    } catch (error: any) {
        console.error('下载模板出错:', error)

        let errorMsg = '下载失败，请检查网络连接'
        if (error.response) {
            if (error.response.status === 401) {
                errorMsg = '下载失败：未授权，请重新登录'
            } else if (error.response.status === 403) {
                errorMsg = '下载失败：权限不足'
            } else if (error.response.status === 500) {
                errorMsg = '下载失败：服务器内部错误'
            } else {
                errorMsg = `下载失败：${error.response.status} - ${error.response.statusText}`
            }
        } else if (error.request) {
            errorMsg = '下载失败：无法连接到服务器'
        }

        ElMessage.error(errorMsg)
    } finally {
        if (loadingInstance) {
            loadingInstance.close()
        }
    }
}

// 选择文件
const handleFileSelect = (file: any) => {
    if (file && file.raw) {
        const selectedFile = file.raw

        // 检查文件类型
        if (!selectedFile.name.endsWith('.xlsx') && !selectedFile.name.endsWith('.xls')) {
            ElMessage.error('只能上传Excel文件(.xlsx或.xls)')
            return
        }

        // 检查文件大小（10MB = 10 * 1024 * 1024 bytes）
        const maxSize = 10 * 1024 * 1024
        if (selectedFile.size > maxSize) {
            ElMessage.error('文件大小不能超过10MB')
            return
        }

        importFile.value = selectedFile
        ElMessage.success(`已选择文件: ${selectedFile.name}`)
    }
}

// 上传文件
const uploadFile = async () => {
    if (!importFile.value) {
        ElMessage.warning('请先选择要导入的文件')
        return
    }

    try {
        importLoading.value = true

        // 创建FormData
        const formData = new FormData()
        formData.append('ImportFile', importFile.value)

        console.log('上传文件:', importFile.value.name)
        console.log('文件大小:', (importFile.value.size / 1024 / 1024).toFixed(2) + 'MB')

        // 调用导入API
        const response = await MES_XHY_ApiHost.post('/api/Scheduling/ImportTeamsData', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

        if (response.data.code === 200) {
            // 保存导入结果
            importResult.value = response.data.data
            console.log('导入结果:', response.data)

            // 判断导入是否完全成功
            if (importResult.value.IsSuccess) {
                ElMessage.success(response.data.msg || '导入成功！')
                // 关闭导入对话框
                showImportDialog.value = false
                importFile.value = null
                // 重新获取班组列表
                await getTeamList()
            } else {
                // 导入部分成功或完全失败，显示结果详情
                showImportResult.value = true
                ElMessage.warning(response.data.msg || '导入完成，但存在失败记录')
            }
        } else {
            ElMessage.error(`导入失败: ${response.data.msg || '未知错误'}`)
        }

    } catch (error: any) {
        console.error('导入文件出错:', error)

        let errorMsg = '导入失败，请检查网络连接'
        if (error.response) {
            if (error.response.status === 401) {
                errorMsg = '导入失败：未授权，请重新登录'
            } else if (error.response.status === 403) {
                errorMsg = '导入失败：权限不足'
            } else if (error.response.status === 400) {
                errorMsg = '导入失败：文件格式错误或数据无效'
            } else if (error.response.status === 500) {
                errorMsg = '导入失败：服务器内部错误'
            } else {
                errorMsg = `导入失败：${error.response.status} - ${error.response.statusText}`
            }
        } else if (error.request) {
            errorMsg = '导入失败：无法连接到服务器'
        }

        ElMessage.error(errorMsg)
    } finally {
        importLoading.value = false
    }
}

// 关闭导入对话框
const closeImportDialog = () => {
    showImportDialog.value = false
    importFile.value = null
}

// 关闭导入结果对话框
const closeImportResult = () => {
    showImportResult.value = false
    importResult.value = null
    // 关闭导入对话框
    showImportDialog.value = false
    importFile.value = null
    // 重新获取班组列表
    getTeamList()
}

const importTeams = () => {
    showImportDialog.value = true
}

const exportTeams = async () => {
    let loadingInstance: any = null

    try {
        // 显示加载状态
        loadingInstance = ElLoading.service({
            lock: true,
            text: '正在导出班组数据...',
            background: 'rgba(0, 0, 0, 0.7)'
        })

        // 构建导出参数
        const exportParams = {
            TeamName: teamSearchQuery.value || '',
            TeamCode: advancedSearchForm.teamCode || '',
            TeamTypeName: advancedSearchForm.teamTypeName || ''
        }

        console.log('导出参数:', exportParams)

        // 调用导出API
        const response = await MES_XHY_ApiHost.get('/api/Scheduling/ExportTeams', {
            params: exportParams,
            responseType: 'blob' // 重要：设置响应类型为blob以处理文件下载
        })

        // 检查响应状态
        if (response.status === 200) {
            // 创建下载链接
            const blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // Excel文件类型
            })

            // 生成文件名
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
            const fileName = `班组数据_${timestamp}.xlsx`

            // 创建下载链接并触发下载
            const downloadLink = document.createElement('a')
            downloadLink.href = URL.createObjectURL(blob)
            downloadLink.download = fileName
            document.body.appendChild(downloadLink)
            downloadLink.click()
            document.body.removeChild(downloadLink)

            // 释放URL对象
            URL.revokeObjectURL(downloadLink.href)

            ElMessage.success('班组数据导出成功！')
            console.log('导出成功，文件名:', fileName)
        } else {
            throw new Error(`导出失败，状态码: ${response.status}`)
        }

    } catch (error: any) {
        console.error('导出班组数据出错:', error)

        let errorMsg = '导出失败，请检查网络连接'
        if (error.response) {
            if (error.response.status === 401) {
                errorMsg = '导出失败：未授权，请重新登录'
            } else if (error.response.status === 403) {
                errorMsg = '导出失败：权限不足'
            } else if (error.response.status === 500) {
                errorMsg = '导出失败：服务器内部错误'
            } else {
                errorMsg = `导出失败：${error.response.status} - ${error.response.statusText}`
            }
        } else if (error.request) {
            errorMsg = '导出失败：无法连接到服务器'
        }

        ElMessage.error(errorMsg)
    } finally {
        // 关闭加载状态
        if (loadingInstance) {
            loadingInstance.close()
        }
    }
}

// 列设置相关方法
const showColumnSettings = () => {
    showColumnSettingsDialog.value = true
}

// 重置列设置
const resetColumnSettings = () => {
    columnSettings.value = [
        { key: 'TeamName', label: '班组名称', visible: true, order: 1, width: 140 },
        { key: 'TeamCode', label: '编组编码', visible: true, order: 2, width: 140 },
        { key: 'TeamTypeName', label: '班组类型', visible: true, order: 3, width: 120 },
        { key: 'Remark', label: '备注', visible: true, order: 4, width: 180 },
        { key: 'Creator', label: '创建人', visible: true, order: 5, width: 120 },
        { key: 'CreatedTime', label: '创建时间', visible: true, order: 6, width: 160 },
        { key: 'Modifier', label: '修改人', visible: true, order: 7, width: 160 },
        { key: 'ModifiedTime', label: '修改时间', visible: true, order: 8, width: 160 }
    ]
    ElMessage.success('列设置已重置')
}

// 确认列设置
const confirmColumnSettings = () => {
    // 保存列设置到本地存储
    localStorage.setItem('teamColumnSettings', JSON.stringify(columnSettings.value))
    showColumnSettingsDialog.value = false
    ElMessage.success('列设置已保存')
}

// 关闭列设置对话框
const closeColumnSettings = () => {
    showColumnSettingsDialog.value = false
}

// 拖拽排序相关方法
const onDragStart = (evt: any, index: number) => {
    evt.dataTransfer.effectAllowed = 'move'
    evt.dataTransfer.setData('text/html', index)
}

const onDragOver = (evt: any) => {
    evt.preventDefault()
    evt.dataTransfer.dropEffect = 'move'
}

const onDrop = (evt: any, targetIndex: number) => {
    evt.preventDefault()
    const sourceIndex = parseInt(evt.dataTransfer.getData('text/html'))

    if (sourceIndex !== targetIndex) {
        const sourceItem = columnSettings.value[sourceIndex]
        const targetItem = columnSettings.value[targetIndex]

        // 交换顺序
        const tempOrder = sourceItem.order
        sourceItem.order = targetItem.order
        targetItem.order = tempOrder

        // 重新排序数组
        columnSettings.value.sort((a, b) => a.order - b.order)
    }
}

const handleTeamSelectionChange = (selection: any[]) => {
    selectedTeams.value = selection
    console.log('选中的班组:', selection.map(team => ({ id: team.TeamsId, name: team.TeamName })))
}

// 清空选择
const clearTeamSelection = () => {
    if (teamTableRef.value) {
        teamTableRef.value.clearSelection()
    }
    selectedTeams.value = []
}

// 全选
const selectAllTeams = () => {
    if (teamTableRef.value) {
        teamList.value.forEach(row => {
            teamTableRef.value.toggleRowSelection(row, true)
        })
    }
}

const handleTeamRowClick = (row: any) => {
    console.log('点击班组行:', row)
    // 保存当前选中的班组ID
    currentSelectedTeamId.value = row.TeamsId
    // 获取班组成员数据
    getMemberList(row.TeamsId)
}

const handleTeamCodeClick = (row: any) => {
    console.log('点击编组编码:', row)
    // 设置选中的班组
    selectedTeams.value = [row]
    // 打开编辑对话框
    showEditTeamDialog.value = true
    // 获取班组详细信息
    editTeamForm.TeamsId = row.TeamsId
    editTeamForm.TeamName = row.TeamName
    editTeamForm.TeamCode = row.TeamCode
    editTeamForm.TeamTypeId = row.TeamTypeId
    editTeamForm.Remark = row.Remark || ''
    
    // 获取班组成员数据
    if (row.TeamsId) {
        getEditTeamMembers(row.TeamsId)
    }
}

const handlePageChange = (page: number) => {
    currentPage.value = page
    getTeamList({
        teamName: teamSearchQuery.value,
        teamCode: advancedSearchForm.teamCode,
        teamTypeName: advancedSearchForm.teamTypeName,
        pageIndex: page
    })
}

const goToSpecificPage = () => {
    const page = parseInt(goToPage.value)
    if (page && page > 0 && page <= totalPages.value) {
        currentPage.value = page
        getTeamList({
            teamName: teamSearchQuery.value,
            teamCode: advancedSearchForm.teamCode,
            teamTypeName: advancedSearchForm.teamTypeName,
            pageIndex: page
        })
        goToPage.value = ''
    }
}

const handlePageSizeChange = (value: number) => {
    pageSize.value = value
    currentPage.value = 1 // 当每页显示条数改变时，重置当前页为1
    getTeamList({
        teamName: teamSearchQuery.value,
        teamCode: advancedSearchForm.teamCode,
        teamTypeName: advancedSearchForm.teamTypeName,
        pageIndex: 1,
        pageSize: value
    })
}

// 成员相关方法
const getMemberList = async (teamsId: number) => {
    if (!teamsId) {
        ElMessage.warning('请先选择班组')
        return
    }

    loading.value = true
    try {
        const response = await MES_XHY_ApiHost.get(`/api/Scheduling/GetTeamMembersByTeamsId/${teamsId}`)

        if (response.data.code === 200) {
            memberList.value = response.data.data
            totalMembers.value = response.data.data.length

            if (memberList.value.length === 0) {
                ElMessage.info('该班组暂无成员数据')
            } else {
                ElMessage.success(`成功获取${totalMembers.value}条成员数据`)
            }
        } else {
            ElMessage.error(`获取班组成员失败: ${response.data.msg || '未知错误'}`)
        }
    } catch (error: any) {
        console.error('获取班组成员出错:', error)
        if (error.response) {
            ElMessage.error(`获取班组成员失败: ${error.response.status} - ${error.response.statusText}`)
        } else if (error.request) {
            ElMessage.error('获取班组成员失败，请检查网络连接')
        } else {
            ElMessage.error('获取班组成员失败，请检查网络连接')
        }
    } finally {
        loading.value = false
    }
}

const handleMemberSelectionChange = (selection: any[]) => {
    selectedMembers.value = selection
}

const handleMemberPageChange = (page: number) => {
    memberCurrentPage.value = page
    if (currentSelectedTeamId.value) {
        getMemberList(currentSelectedTeamId.value)
    }
}

const goToSpecificMemberPage = () => {
    const page = parseInt(memberGoToPage.value)
    if (page && page > 0) {
        memberCurrentPage.value = page
        memberGoToPage.value = ''
    }
}

// 获取班组类型标签类型
const getTeamTypeTagType = (typeName: string) => {
    switch (typeName) {
        case '仓库':
            return 'info'
        case '组装':
            return 'success'
        case '注塑':
            return 'warning'
        case '机加工':
            return 'danger'
        default:
            return 'default'
    }
}

// 班组新增相关方法
const showCreateTeam = () => {
    showCreateTeamDialog.value = true
    
    // 重置表单数据
    Object.assign(createTeamForm, {
        TeamName: '',
        TeamCode: '',
        TeamTypeId: null,
        Remark: '',
        Creator: 'admin'
    })
    
    // 清空成员表格数据
    memberTableData.value = []
    selectedMemberRows.value = []
    memberTableCurrentPage.value = 1
    memberTablePageSize.value = 100
    memberTableGoToPage.value = ''
    
    // 重置表单验证状态
    if (createTeamFormRef.value) {
        createTeamFormRef.value.clearValidate()
    }
}

const closeCreateTeamDialog = () => {
    showCreateTeamDialog.value = false
}

const saveTeam = async () => {
    if (!createTeamFormRef.value) return

    await createTeamFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            saveLoading.value = true
            try {
                // 第一步：创建班组
                const teamResponse = await MES_XHY_ApiHost.post('/api/Scheduling/CreateTeams', createTeamForm)

                if (teamResponse.data.code === 200) {
                    const teamId = teamResponse.data.data?.TeamsId || teamResponse.data.data?.TeamId
                    
                    if (teamId && memberTableData.value.length > 0) {
                        // 第二步：逐个创建班组成员，避免批量创建的数据长度问题
                        console.log(`开始逐个创建${memberTableData.value.length}个班组成员`)
                        
                        let successCount = 0
                        let failureCount = 0
                        
                        for (let i = 0; i < memberTableData.value.length; i++) {
                            const member = memberTableData.value[i]
                            
                            try {
                                // 检查成员数据的完整性
                                console.log(`原始成员数据:`, member)
                                
                                // 验证必填字段
                                if (!member.MemberName?.trim()) {
                                    console.error(`第${i + 1}个成员缺少成员名称`)
                                    failureCount++
                                    continue
                                }
                                
                                if (!member.MemberRealName?.trim()) {
                                    console.error(`第${i + 1}个成员缺少成员真实姓名`)
                                    failureCount++
                                    continue
                                }
                                
                                // 为每个成员创建最小的请求参数
                                const individualMemberParams = {
                                    TeamsId: teamId,
                                    Members: [{
                                        MemberName: member.MemberName.trim(),
                                        MemberRealName: member.MemberRealName.trim(),
                                        PhoneNumber: (member.PhoneNumber || '').trim(),
                                        Creator: member.Creator || 'admin'
                                    }],
                                    UserId: 1,
                                    UserName: 'admin'
                                }
                                
                                console.log(`创建第${i + 1}个成员:`, individualMemberParams)
                                console.log(`请求参数JSON长度:`, JSON.stringify(individualMemberParams).length)
                                
                                const memberResponse = await MES_XHY_ApiHost.post('/api/Scheduling/BatchCreateTeamMembers', individualMemberParams)
                                
                                if (memberResponse.data.code === 200) {
                                    successCount++
                                    console.log(`第${i + 1}个成员创建成功:`, memberResponse.data.data)
                                } else {
                                    failureCount++
                                    console.error(`第${i + 1}个成员创建失败:`, memberResponse.data)
                                }
                            } catch (memberError: any) {
                                failureCount++
                                console.error(`第${i + 1}个成员创建出错:`, memberError)
                                
                                // 提供更详细的错误信息
                                if (memberError.response) {
                                    if (memberError.response.data && memberError.response.data.msg) {
                                        console.error(`服务器错误信息: ${memberError.response.data.msg}`)
                                    } else if (memberError.response.status) {
                                        console.error(`HTTP状态码: ${memberError.response.status}`)
                                    }
                                } else if (memberError.message) {
                                    console.error(`错误消息: ${memberError.message}`)
                                }
                            }
                            
                            // 添加小延迟，避免请求过于频繁
                            if (i < memberTableData.value.length - 1) {
                                await new Promise(resolve => setTimeout(resolve, 100))
                            }
                        }
                        
                        // 显示最终结果
                        if (failureCount === 0) {
                            ElMessage.success(`${teamResponse.data.msg}，成功创建${successCount}个班组成员`)
                        } else if (successCount === 0) {
                            ElMessage.warning(`${teamResponse.data.msg}，但所有班组成员创建失败`)
                        } else {
                            ElMessage.warning(`${teamResponse.data.msg}，班组成员部分创建成功：成功${successCount}个，失败${failureCount}个`)
                        }
                    } else {
                        ElMessage.success(teamResponse.data.msg || '班组新增成功！')
                    }
                    
                    showCreateTeamDialog.value = false
                    // 重新获取班组列表
                    await getTeamList()
                } else {
                    ElMessage.error(`新增失败: ${teamResponse.data.msg || '未知错误'}`)
                }
            } catch (error: any) {
                console.error('新增班组出错:', error)
                if (error.response) {
                    let errorMsg = `新增班组失败: ${error.response.status} - ${error.response.statusText}`
                    if (error.response.data && error.response.data.msg) {
                        errorMsg = `新增班组失败: ${error.response.data.msg}`
                    } else if (error.response.data && error.response.data.message) {
                        errorMsg = `新增班组失败: ${error.response.data.message}`
                    }
                    ElMessage.error(errorMsg)
                } else if (error.request) {
                    ElMessage.error('新增班组失败，请检查网络连接')
                } else {
                    ElMessage.error('新增班组失败，请检查网络连接')
                }
            } finally {
                saveLoading.value = false
            }
        } else {
            ElMessage.error('请检查输入信息')
        }
    })
}

const selectExistingUsers = () => {
    isSelectingForEdit.value = false
    showSelectUsersDialog.value = true
    userSearchQuery.value = ''
    userList.value = []
    selectedUsers.value = []
    
    // 自动获取所有用户信息
    searchUsers()
}

const searchUsers = async () => {
    try {
        // 使用正确的API接口获取用户，支持按账号查询
        const params = userSearchQuery.value ? { Account: userSearchQuery.value } : {}
        const response = await MES_XHY_ApiHost.get('/api/Login/getAllUsers', { params })
        
        if (response.data.code === 200) {
            userList.value = response.data.data
            if (userList.value.length === 0) {
                ElMessage.info('暂无用户数据')
            } else {
                ElMessage.success(`成功获取 ${userList.value.length} 个用户`)
            }
        } else {
            ElMessage.error(`获取用户失败: ${response.data.msg || '未知错误'}`)
        }
    } catch (error: any) {
        console.error('获取用户出错:', error)
        if (error.response) {
            ElMessage.error(`获取用户失败: ${error.response.status} - ${error.response.statusText}`)
        } else if (error.request) {
            ElMessage.error('获取用户失败，请检查网络连接')
        } else {
            ElMessage.error('获取用户失败，请检查网络连接')
        }
    }
}

const handleUserSelectionChange = (selection: any[]) => {
    selectedUsers.value = selection
}

const confirmSelectUsers = () => {
    if (selectedUsers.value.length === 0) {
        ElMessage.warning('请选择要添加的用户')
        return
    }
    
    console.log('选中的用户数据:', selectedUsers.value)
    
    // 将选中的用户转换为成员格式，使用正确的字段名
    const newMembers = selectedUsers.value.map(user => {
        console.log('处理用户:', user)
        
        const newMember = {
            TeamMembersId: 0, // 新成员ID为0
            MemberName: user.Account || user.UserName || user.Username || '', // 尝试多个可能的字段名
            MemberRealName: user.Name || user.RealName || user.DisplayName || '', // 尝试多个可能的字段名
            PhoneNumber: user.QQNumber1 || user.QQNumber2 || user.Phone || user.PhoneNumber || '', // 尝试多个可能的字段名
            Creator: 'admin',
            CreatedTime: formatDateTime(new Date().toISOString()),
            Modifier: '', // 新添加的成员修改人为空
            ModifiedTime: '' // 新添加的成员修改时间为空
        }
        
        console.log('转换后的成员数据:', newMember)
        return newMember
    })
    
    memberTableData.value = [...memberTableData.value, ...newMembers]
    selectedUsers.value = []
    showSelectUsersDialog.value = false
    ElMessage.success(`已添加 ${newMembers.length} 个用户`)
    
    console.log('更新后的memberTableData:', memberTableData.value)
}

const addMemberRow = () => {
    const newRow = {
        MemberName: '',
        MemberRealName: '',
        PhoneNumber: '',
        Creator: 'admin',
        CreatedTime: formatDateTime(new Date().toISOString()),
        Modifier: '', // 新行修改人为空
        ModifiedTime: '' // 新行修改时间为空
    }
    memberTableData.value.push(newRow)
    selectedMemberRows.value = [] // 清空选中状态
}

const deleteSelectedRows = () => {
    if (selectedMemberRows.value.length === 0) {
        ElMessage.warning('请选择要删除的行')
        return
    }
    
    const selectedIds = selectedMemberRows.value.map(row => memberTableData.value.indexOf(row))
    memberTableData.value = memberTableData.value.filter((_, index) => !selectedIds.includes(index))
    selectedMemberRows.value = []
    ElMessage.success(`已删除 ${selectedIds.length} 行`)
}

const refreshMemberTable = () => {
    // 重新获取当前页的数据
    const start = (memberTableCurrentPage.value - 1) * memberTablePageSize.value
    const end = start + memberTablePageSize.value
    memberTableData.value = memberTableData.value.slice(start, end)
}

const goToSpecificMemberTablePage = () => {
    const page = parseInt(memberTableGoToPage.value)
    if (page && page > 0) {
        memberTableCurrentPage.value = page
        refreshMemberTable()
        memberTableGoToPage.value = ''
    }
}

// 页面加载时获取数据
onMounted(() => {
    getTeamTypeList()
    getTeamList()
    // 清空成员数据
    memberList.value = []
    totalMembers.value = 0
    currentSelectedTeamId.value = null

    // 从本地存储恢复列设置
    const savedSettings = localStorage.getItem('teamColumnSettings')
    if (savedSettings) {
        try {
            columnSettings.value = JSON.parse(savedSettings)
        } catch (error) {
            console.error('恢复列设置失败:', error)
        }
    }
})

// 添加缺失的方法
const importMembers = () => {
    ElMessage.info('导入功能待实现')
}

const handleMemberRowSelectionChange = (selection: any[]) => {
    selectedMemberRows.value = selection
}

const handleConfirmSelectUsers = () => {
    console.log('确认选择用户按钮被点击，isSelectingForEdit:', isSelectingForEdit.value)
    console.log('选中的用户数量:', selectedUsers.value.length)
    
    if (isSelectingForEdit.value) {
        console.log('调用 confirmSelectUsersForEdit')
        confirmSelectUsersForEdit()
    } else {
        console.log('调用 confirmSelectUsers')
        confirmSelectUsers()
    }
}

const closeSelectUsersDialog = () => {
    showSelectUsersDialog.value = false
    selectedUsers.value = []
    isSelectingForEdit.value = false
}

// 班组编辑相关方法
const getEditTeamMembers = async (teamsId: number) => {
    try {
        const response = await MES_XHY_ApiHost.get(`/api/Scheduling/GetTeamMembersByTeamsId/${teamsId}`)
        
        if (response.data.code === 200) {
            editMemberTableData.value = response.data.data || []
            editMemberTableTotal.value = editMemberTableData.value.length
            editMemberTableCurrentPage.value = 1
        } else {
            ElMessage.error(`获取班组成员失败: ${response.data.msg || '未知错误'}`)
        }
    } catch (error: any) {
        console.error('获取编辑班组成员出错:', error)
        ElMessage.error('获取班组成员失败，请检查网络连接')
    }
}

const saveEditTeam = async () => {
    if (!editTeamFormRef.value) return

    await editTeamFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // 数据验证：检查成员数据长度
            if (editMemberTableData.value.length > 0) {
                const validMembers = editMemberTableData.value.filter(member => 
                    member.MemberName && member.MemberRealName && member.MemberName.trim() && member.MemberRealName.trim()
                )
                
                // 检查每个成员字段的长度
                for (let i = 0; i < validMembers.length; i++) {
                    const member = validMembers[i]
                    if (member.MemberName && member.MemberName.length > 100) {
                        ElMessage.error(`第${i + 1}行成员名称过长，请控制在100字符以内`)
                        return
                    }
                    if (member.MemberRealName && member.MemberRealName.length > 100) {
                        ElMessage.error(`第${i + 1}行成员真实姓名过长，请控制在100字符以内`)
                        return
                    }
                    if (member.PhoneNumber && member.PhoneNumber.length > 20) {
                        ElMessage.error(`第${i + 1}行电话号码过长，请控制在20字符以内`)
                        return
                    }
                }
            }
            
            editSaveLoading.value = true
            try {
                // 第一步：调用编辑班组API
                const editParams = {
                    TeamsId: editTeamForm.TeamsId,
                    TeamName: editTeamForm.TeamName,
                    TeamCode: editTeamForm.TeamCode,
                    TeamTypeId: editTeamForm.TeamTypeId,
                    Remark: editTeamForm.Remark,
                    Modifier: editTeamForm.Modifier
                }

                console.log('编辑班组请求参数:', editParams)
                console.log('API地址: MES_XHY_ApiHost/api/Scheduling/UpdateTeams')

                const teamResponse = await MES_XHY_ApiHost.put('/api/Scheduling/UpdateTeams', editParams)

                if (teamResponse.data.code === 200) {
                    console.log('班组编辑成功返回数据:', teamResponse.data.data)
                    
                                            // 第二步：如果有班组成员数据，调用逐个更新班组成员API
                    if (editMemberTableData.value.length > 0) {
                        try {
                            // 准备班组成员数据，过滤掉空行和无效数据
                            const validMembers = editMemberTableData.value.filter(member => 
                                member.MemberName && member.MemberRealName && member.MemberName.trim() && member.MemberRealName.trim()
                            )
                            
                            if (validMembers.length > 0) {
                                // 直接使用逐个更新方式，避免批量更新的数据长度问题
                                console.log(`开始逐个更新${validMembers.length}个班组成员`)
                                ElMessage.info('正在逐个更新班组成员，请稍候...')
                                
                                const individualSuccessCount = await updateMembersIndividually(validMembers, editTeamForm.TeamsId)
                                
                                if (individualSuccessCount > 0) {
                                    ElMessage.success(`${teamResponse.data.msg}，成功更新${individualSuccessCount}个班组成员`)
                                } else {
                                    ElMessage.warning(`${teamResponse.data.msg}，但所有班组成员更新失败`)
                                }
                            } else {
                                ElMessage.success(teamResponse.data.msg || '班组编辑成功！')
                            }
                        } catch (memberError: any) {
                            console.error('逐个更新班组成员出错:', memberError)
                            
                            // 提供更详细的错误信息
                            let memberErrorMsg = '班组成员更新失败'
                            if (memberError.response) {
                                if (memberError.response.data && memberError.response.data.msg) {
                                    memberErrorMsg = `班组成员更新失败: ${memberError.response.data.msg}`
                                } else if (memberError.response.status) {
                                    memberErrorMsg = `班组成员更新失败: HTTP ${memberError.response.status}`
                                }
                            } else if (memberError.message) {
                                memberErrorMsg = `班组成员更新失败: ${memberError.message}`
                            }
                            
                            ElMessage.warning(`${teamResponse.data.msg}，但${memberErrorMsg}`)
                        }
                    } else {
                        ElMessage.success(teamResponse.data.msg || '班组编辑成功！')
                    }
                    
                    // 关闭编辑对话框
                    showEditTeamDialog.value = false
                    
                    // 重新获取班组列表
                    await getTeamList()
                } else {
                    ElMessage.error(`编辑失败: ${teamResponse.data.msg || '未知错误'}`)
                }
            } catch (error: any) {
                console.error('编辑班组出错:', error)
                if (error.response) {
                    let errorMsg = `编辑班组失败: ${error.response.status} - ${error.response.statusText}`
                    if (error.response.data && error.response.data.msg) {
                        errorMsg = `编辑班组失败: ${error.response.data.msg}`
                    } else if (error.response.data && error.response.data.message) {
                        errorMsg = `编辑班组失败: ${error.response.data.message}`
                    }
                    ElMessage.error(errorMsg)
                } else if (error.request) {
                    ElMessage.error('编辑班组失败，请检查网络连接')
                } else {
                    ElMessage.error('编辑班组失败，请检查网络连接')
                }
            } finally {
                editSaveLoading.value = false
            }
        } else {
            ElMessage.error('请检查输入信息')
        }
    })
}

const closeEditTeamDialog = () => {
    showEditTeamDialog.value = false
    // 重置编辑表单
    Object.assign(editTeamForm, {
        TeamsId: 0,
        TeamName: '',
        TeamCode: '',
        TeamTypeId: null,
        Remark: '',
        Modifier: 'admin'
    })
    // 清空编辑成员表格数据
    editMemberTableData.value = []
    selectedEditMemberRows.value = []
    editMemberTableCurrentPage.value = 1
    editMemberTablePageSize.value = 100
    editMemberTableGoToPage.value = ''
    editMemberTableTotal.value = 0
}

// 编辑班组成员相关方法
const selectExistingUsersForEdit = () => {
    isSelectingForEdit.value = true
    showSelectUsersDialog.value = true
    userSearchQuery.value = ''
    userList.value = []
    selectedUsers.value = []
    // 自动获取所有用户信息
    searchUsers()
}

// 确认选择用户到编辑成员表格
const confirmSelectUsersForEdit = () => {
    if (selectedUsers.value.length === 0) {
        ElMessage.warning('请选择要添加的用户')
        return
    }
    
    // 将选中的用户转换为成员格式，使用正确的字段名
    const newMembers = selectedUsers.value.map(user => ({
        TeamMembersId: 0, // 新成员ID为0
        MemberName: user.Account || '', // 使用Account作为成员名称
        MemberRealName: user.Name || '', // 使用Name作为成员真实姓名
        PhoneNumber: user.QQNumber1 || user.QQNumber2 || '', // 使用QQ号作为电话号码
        Creator: 'admin',
        CreatedTime: formatDateTime(new Date().toISOString()),
        Modifier: '', // 新添加的成员修改人为空
        ModifiedTime: '' // 新添加的成员修改时间为空
    }))
    
    editMemberTableData.value = [...editMemberTableData.value, ...newMembers]
    selectedUsers.value = []
    showSelectUsersDialog.value = false
    ElMessage.success(`已添加 ${newMembers.length} 个用户到编辑表格`)
}

const addEditMemberRow = () => {
    const newRow = {
        TeamMembersId: 0, // 新成员ID为0
        MemberName: '',
        MemberRealName: '',
        PhoneNumber: '',
        Creator: 'admin',
        CreatedTime: formatDateTime(new Date().toISOString()),
        Modifier: '',
        ModifiedTime: ''
    }
    editMemberTableData.value.push(newRow)
}

const deleteSelectedEditRows = () => {
    if (selectedEditMemberRows.value.length === 0) {
        ElMessage.warning('请选择要删除的行')
        return
    }
    
    const selectedIds = selectedEditMemberRows.value.map(row => editMemberTableData.value.indexOf(row))
    selectedIds.sort((a, b) => b - a) // 从大到小排序，避免索引变化
    
    selectedIds.forEach(index => {
        editMemberTableData.value.splice(index, 1)
    })
    
    selectedEditMemberRows.value = []
    ElMessage.success(`已删除 ${selectedIds.length} 行`)
}

const importEditMembers = () => {
    ElMessage.info('导入功能待实现')
}

const exportEditMembers = async () => {
    if (!editTeamForm.TeamsId) {
        ElMessage.warning('请先选择要导出的班组')
        return
    }
    
    try {
        ElMessage.info('正在导出班组成员数据，请稍候...')
        
        // 调用导出API，使用班组ID作为路径参数
        const response = await MES_XHY_ApiHost.get(`/api/Scheduling/ExportTeamMembers/${editTeamForm.TeamsId}`, {
            responseType: 'blob' // 设置响应类型为blob，用于文件下载
        })
        
        // 检查响应状态
        if (response.status === 200) {
            // 创建下载链接
            const blob = new Blob([response.data], { 
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // Excel文件类型
            })
            
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            
            // 设置文件名，包含班组名称和当前时间
            const teamName = editTeamForm.TeamName || '班组'
            const currentTime = new Date().toISOString().slice(0, 10).replace(/-/g, '')
            link.download = `${teamName}_成员列表_${currentTime}.xlsx`
            
            // 触发下载
            document.body.appendChild(link)
            link.click()
            
            // 清理
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
            
            ElMessage.success('班组成员数据导出成功！')
        } else {
            ElMessage.error('导出失败，请重试')
        }
    } catch (error: any) {
        console.error('导出班组成员出错:', error)
        
        let errorMsg = '导出失败'
        if (error.response) {
            if (error.response.data && error.response.data.msg) {
                errorMsg = `导出失败: ${error.response.data.msg}`
            } else if (error.response.status) {
                errorMsg = `导出失败: HTTP ${error.response.status}`
            }
        } else if (error.message) {
            errorMsg = `导出失败: ${error.message}`
        }
        
        ElMessage.error(errorMsg)
    }
}

const refreshEditMemberTable = () => {
    if (editTeamForm.TeamsId) {
        getEditTeamMembers(editTeamForm.TeamsId)
    }
}

const handleEditMemberRowSelectionChange = (selection: any[]) => {
    selectedEditMemberRows.value = selection
}

const handleEditMemberSizeChange = (size: number) => {
    editMemberTablePageSize.value = size
    editMemberTableCurrentPage.value = 1
}

const handleEditMemberCurrentChange = (page: number) => {
    editMemberTableCurrentPage.value = page
}

// 逐个更新班组成员的备用方案
const updateMembersIndividually = async (members: any[], teamsId: number): Promise<number> => {
    let successCount = 0
    
    for (let i = 0; i < members.length; i++) {
        const member = members[i]
        
        try {
            // 为每个成员创建最小的请求参数，包含必要的验证字段
            const individualParams = {
                TeamsId: teamsId,
                Members: [{
                    TeamMembersId: member.TeamMembersId || 0,
                    MemberName: member.MemberName.trim(),
                    MemberRealName: member.MemberRealName.trim(),
                    PhoneNumber: (member.PhoneNumber || '').trim(),
                    Modifier: 'admin'
                }],
                // 添加后端验证所需的字段
                UserId: 1,
                UserName: 'admin'
            }
            
            console.log(`逐个更新第${i + 1}个成员:`, individualParams)
            
            const response = await MES_XHY_ApiHost.put('/api/Scheduling/BatchUpdateTeamMembers', individualParams)
            
            if (response.data.code === 200) {
                successCount++
                console.log(`第${i + 1}个成员更新成功:`, response.data.data)
            } else {
                console.error(`第${i + 1}个成员更新失败:`, response.data)
            }
        } catch (error: any) {
            console.error(`第${i + 1}个成员更新出错:`, error)
        }
        
        // 添加小延迟，避免请求过于频繁
        if (i < members.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 100))
        }
    }
    
    return successCount
}
</script>

<style scoped>
.team-management-container {
    padding: 10px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.team-section,
.team-member-section {
    background-color: white;
    border-radius: 6px;
    padding: 10px;
    margin-bottom: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    max-width: 100%;
    overflow-x: auto;
}

.section-title {
    font-size: 13px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
    padding-bottom: 6px;
    border-bottom: 1px solid #e4e7ed;
}

.search-action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    flex-wrap: wrap;
    gap: 4px;
}

.left-section,
.right-section {
    display: flex;
    gap: 4px;
    align-items: center;
    flex-wrap: wrap;
}

.search-input {
    width: 200px;
}

.advanced-search-section {
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid #eee;
}

.search-criteria {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 8px;
}

.criteria-item {
    display: flex;
    align-items: center;
    gap: 4px;
}

.criteria-item label {
    font-size: 10.5px;
    color: #555;
    min-width: 68px;
}

.criteria-input {
    width: 200px;
}

.criteria-select {
    width: 200px;
}

.search-actions {
    display: flex;
    justify-content: flex-end;
    gap: 6px;
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 8px;
    gap: 6px;
    flex-wrap: wrap;
}

.total-count {
    color: #666;
    font-size: 10.5px;
}

.page-size-select {
    width: 90px;
}

.go-to-page {
    display: flex;
    align-items: center;
    gap: 3px;
    color: #666;
    font-size: 10.5px;
}

.page-input {
    width: 38px;
}

:deep(.el-table) {
    margin-bottom: 8px;
    font-size: 11px;
}

/* 控件更紧凑尺寸（再降） */
:deep(.el-button) {
    border-radius: 4px;
    padding: 2px 6px;
    font-size: 11.5px;
    height: 24px;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
    height: 26px;
    padding: 0 6px;
    font-size: 11.5px;
}

:deep(.el-select) {
    border-radius: 4px;
}

:deep(.el-loading-mask) {
    background-color: rgba(255, 255, 255, 0.8);
}

:deep(.el-loading-spinner) {
    margin-top: -20px;
}

.team-type-tag {
    border-radius: 12px;
    font-weight: 500;
    min-width: 60px;
    text-align: center;
}

.team-type-tag.el-tag--success {
    background-color: #f0f9ff;
    border-color: #91d5ff;
    color: #1890ff;
}

.team-type-tag.el-tag--info {
    background-color: #f6ffed;
    border-color: #b7eb8f;
    color: #52c41a;
}

.team-type-tag.el-tag--warning {
    background-color: #fff7e6;
    border-color: #ffd591;
    color: #fa8c16;
}

.team-type-tag.el-tag--danger {
    background-color: #fff2f0;
    border-color: #ffccc7;
    color: #ff4d4f;
}

.team-type-tag.el-tag--default {
    background-color: #f5f5f5;
    border-color: #d9d9d9;
    color: #666;
}

.info-status-bar {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e9ecef;
}



.selection-status {
    display: flex;
    align-items: center;
    gap: 10px;
}

/* 删除确认对话框样式 */
:deep(.delete-confirm-dialog) {
    .el-message-box__content {
        text-align: center;
    }

    .el-message-box__message {
        line-height: 1.6;
    }

    .el-message-box__btns {
        justify-content: center;
        gap: 15px;
    }
}

/* 导入对话框样式 */
.import-dialog-content {
    padding: 20px 0;
}

.import-actions {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    justify-content: center;
}

.file-upload-area {
    margin-bottom: 20px;
}

.selected-file {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
    justify-content: center;
}

.file-size {
    color: #666;
    font-size: 12px;
}

.upload-instructions {
    margin-top: 20px;
}

.upload-instructions .el-alert {
    margin-bottom: 0;
}

.upload-instructions p {
    margin: 5px 0;
    font-size: 14px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

@media (max-width: 768px) {
    .search-action-bar {
        flex-direction: column;
        align-items: stretch;
    }

    .left-section,
    .right-section {
        justify-content: center;
    }

    .pagination-container {
        flex-direction: column;
        gap: 10px;
    }

    .import-actions {
        flex-direction: column;
        align-items: center;
    }
}

/* 导入结果对话框样式 */
.import-result-content {
    padding: 20px 0;
}

.import-summary {
    margin-bottom: 30px;
}

.summary-item {
    text-align: center;
    padding: 20px;
    border-radius: 8px;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
}

.summary-item.success {
    background-color: #f6ffed;
    border-color: #b7eb8f;
}

.summary-item.danger {
    background-color: #fff2f0;
    border-color: #ffccc7;
}

.summary-number {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
}

.summary-item.success .summary-number {
    color: #52c41a;
}

.summary-item.danger .summary-number {
    color: #ff4d4f;
}

.summary-label {
    font-size: 14px;
    color: #666;
}

.success-section,
.failure-section,
.error-section {
    margin-bottom: 20px;
}

.success-section h4,
.failure-section h4,
.error-section h4 {
    margin: 0 0 15px 0;
    font-size: 16px;
    color: #333;
    font-weight: 600;
}

.team-id-tag,
.row-number-tag {
    margin: 0 8px 8px 0;
    font-size: 12px;
}

.error-list {
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    padding: 10px;
    background-color: #fafafa;
}

.error-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
}

.error-item:last-child {
    border-bottom: none;
}

.error-icon {
    color: #ff4d4f;
    font-size: 14px;
}

.error-text {
    color: #333;
    font-size: 14px;
    line-height: 1.4;
}

/* 列设置对话框样式 */
.column-settings-content {
    padding: 20px 0;
}

.drag-tip {
    margin-bottom: 20px;
}

.column-list {
    margin-top: 20px;
}

.drag-handle {
    cursor: move;
    color: #409eff;
    font-size: 16px;
    padding: 5px;
    border-radius: 4px;
    transition: all 0.3s;
}

.drag-handle:hover {
    background-color: #f0f9ff;
    color: #1890ff;
}

.drag-handle:active {
    background-color: #e6f7ff;
    transform: scale(0.95);
}

/* 拖拽时的视觉反馈 */
.column-list .el-table tr {
    transition: all 0.3s;
}

.column-list .el-table tr:hover {
    background-color: #f5f7fa;
}

/* 表格响应式优化 */
.el-table {
    width: 100% !important;
}

.el-table__body-wrapper {
    overflow-x: auto;
}

/* 优化表格列间距（更紧凑-再降到极致仍可读） */
.el-table th.el-table__cell,
.el-table td.el-table__cell {
    padding: 3px 6px;
}

/* 表格容器优化 */
.team-section .el-table {
    margin: 0;
    border-radius: 6px;
    overflow: hidden;
}

/* 响应式布局优化 */
@media (max-width: 1200px) {
    .search-action-bar {
        gap: 10px;
    }

    .left-section,
    .right-section {
        gap: 8px;
    }
}

@media (max-width: 768px) {
    .team-section {
        padding: 15px;
    }

    .search-action-bar {
        flex-direction: column;
        align-items: stretch;
        gap: 15px;
    }

    .left-section,
    .right-section {
        justify-content: center;
        gap: 10px;
        flex-wrap: wrap;
    }

    .pagination-container {
        flex-direction: column;
        gap: 10px;
    }

    .import-actions {
        flex-direction: column;
        align-items: center;
    }

    /* 移动端表格优化 */
    .el-table {
        font-size: 12px;
    }

    .el-table th.el-table__cell,
    .el-table td.el-table__cell {
        padding: 6px 8px;
    }
}

/* 班组新增对话框样式 */
.create-team-content {
    padding: 20px 0;
}

/* 班组编辑对话框样式 */
.edit-team-content {
    padding: 20px 0;
}

.team-info-section,
.team-member-section {
    margin-bottom: 30px;
}

.section-subtitle {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    align-items: center;
    gap: 8px;
}

.member-actions {
    display: flex;
    gap: 4px;
    margin-bottom: 8px;
    flex-wrap: wrap;
}

.member-pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 8px;
    gap: 6px;
    flex-wrap: wrap;
}

/* 可点击的编组编码样式 */
.clickable-team-code {
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
    transition: color 0.3s ease;
}

.clickable-team-code:hover {
    color: #66b1ff;
    text-decoration: none;
}

.clickable-team-code:active {
    color: #3a8ee6;
}

/* 选择用户对话框样式 */
.select-users-content {
    padding: 20px 0;
}

.user-search-bar {
    display: flex;
    gap: 8px;
    margin-bottom: 10px;
    align-items: center;
}

/* 响应式布局优化 */
@media (max-width: 1200px) {
    .search-action-bar {
        gap: 10px;
    }

    .left-section,
    .right-section {
        gap: 8px;
    }
}

/* 时间显示切换开关样式 */
.time-display-toggle {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 8px;
}

.time-display-toggle .el-switch {
    margin-left: 0;
}

/* 相对时间显示样式 */
.el-table .relative-time {
    color: #409eff;
    font-weight: 500;
}

.el-table .absolute-time {
    color: #606266;
}

/* 响应式布局优化 */
@media (max-width: 1200px) {
    .search-action-bar {
        gap: 10px;
    }

    .left-section,
    .right-section {
        gap: 8px;
    }
    
    /* 在小屏幕上隐藏时间显示切换开关的文字 */
    .el-switch__label {
        display: none;
    }
}
</style>